from rest_framework import serializers
from rest_framework.exceptions import AuthenticationFailed

from account.models import User
from account.services import AccountService
from utils.decorators.swagger import data_response_decorator
from utils.handlers.exception import CommonError
from utils.mixins.common_mixins.logger import common_logger


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'last_login', 'email')


# noinspection PyAbstractClass
class LoginSerializer(serializers.Serializer):
    """接口文档登录-序列化器"""
    username = serializers.CharField(required=True, min_length=2, max_length=100, help_text='用户名')

    password = serializers.CharField(required=True, min_length=1, max_length=100, help_text='密码')

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        user_instance = User.objects.filter(username=username).last()
        if not (user_instance and user_instance.check_password(password)):
            raise AuthenticationFailed('用户名或密码错误')
        account_service = AccountService(user=user_instance)

        ret = {
            'userinfo': UserSerializer(account_service.user, many=False).data,
            'roles': account_service.user.get_user_groups(),
            'tokens': account_service.get_token(),
        }
        common_logger.info(f'用户 {username} 登录成功, 返回信息: {ret}')
        return ret


class UserInfo(serializers.Serializer):
    id = serializers.IntegerField()
    username = serializers.CharField()
    first_name = serializers.CharField(allow_blank=True)
    last_name = serializers.CharField(allow_blank=True)
    email = serializers.CharField(allow_blank=True)


class Permissions(serializers.Serializer):
    name = serializers.CharField()
    code = serializers.CharField()
    description = serializers.CharField()


class Tokens(serializers.Serializer):
    access = serializers.CharField()
    refresh = serializers.CharField()


@data_response_decorator()
class LoginResponseSerializer(serializers.Serializer):
    userinfo = UserInfo()
    permissions = serializers.DictField(child=serializers.ListField(child=Permissions()))
    roles = serializers.ListSerializer(child=serializers.CharField())
    tokens = Tokens()


class TestSerializer(serializers.Serializer):

    def validate(self, attrs):
        # raise CommonError('测试错误')
        return attrs

@data_response_decorator()
class TestResponseSerializer(serializers.Serializer):
    pass